package action.common;

import java.io.File;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import net.fckeditor.connector.Messages;
import net.fckeditor.handlers.CommandHandler;
import net.fckeditor.handlers.ConnectorHandler;
import net.fckeditor.handlers.ExtensionsHandler;
import net.fckeditor.handlers.RequestCycleHandler;
import net.fckeditor.handlers.ResourceTypeHandler;
import net.fckeditor.response.UploadResponse;
import net.fckeditor.tool.UtilsFile;
import net.fckeditor.tool.UtilsResponse;

import org.apache.commons.io.FilenameUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.aspectj.util.FileUtil;

import com.opensymphony.xwork2.ActionSupport;

public class FckUploadAction extends ActionSupport implements ServletRequestAware {

    private static final long serialVersionUID = -8348724468538176453L;

    private HttpServletRequest request;
    
    public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }

    public String fckeditorDocUpload() throws Exception {

        ServletActionContext.getResponse().setCharacterEncoding("utf-8");
        PrintWriter out = ServletActionContext.getResponse().getWriter();
        UploadResponse ur = fckeditorProcessRequest(request, "File", "QuickUpload", "/bulletin/", 1024000);

        out.print(ur);
        out.flush();
        out.close();
        return SUCCESS;
    }

    private UploadResponse fckeditorProcessRequest(HttpServletRequest request, String typeStr, String commandStr, String currentFolderStr, long maxSize) {

        UploadResponse ur = new UploadResponse(UploadResponse.SC_ERROR);

        if (!RequestCycleHandler.isEnabledForFileUpload(request)) {
            return new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null, Messages.NOT_AUTHORIZED_FOR_UPLOAD);
        } else if (!CommandHandler.isValidForPost(commandStr)) {
            return new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND);
        } else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr)) {
            return new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE);
        } else if (!UtilsFile.isValidPath(currentFolderStr)) {
            return UploadResponse.UR_INVALID_CURRENT_FOLDER;
        } else {
            ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);

            String typePath = UtilsFile.constructServerSidePath(request, resourceType);
            String typeDirPath = request.getSession().getServletContext().getRealPath(typePath);

            File typeDir = new File(typeDirPath);
            UtilsFile.checkDirAndCreate(typeDir);

            File currentDir = new File(typeDir, currentFolderStr);
            UtilsFile.checkDirAndCreate(currentDir);
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String todayDirStr = sdf.format(new Date());

            File todayDir = new File(currentDir, todayDirStr);
            UtilsFile.checkDirAndCreate(todayDir);

            MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) request;
            if (multiWrapper.getErrors() != null && !multiWrapper.getErrors().isEmpty()) {
                return new UploadResponse(UploadResponse.SC_ERROR, null, null, multiWrapper.getErrors().toArray()[0].toString());
            }

            Enumeration<String> fieldNames = multiWrapper.getFileParameterNames();

            while (fieldNames != null && fieldNames.hasMoreElements()) {
                String fieldName = fieldNames.nextElement();
                File[] files = multiWrapper.getFiles(fieldName);
                String[] names = multiWrapper.getFileNames(fieldName);
                for (int i = 0; i < files.length; i++) {

                    String extension = FilenameUtils.getExtension(names[i]);

                    if (!ExtensionsHandler.isAllowed(resourceType, extension)) {
                        return new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                    } else if (files[i].length() > maxSize) {
                        // 文件过大
                        return new UploadResponse(UploadResponse.SC_ERROR, null, null, "只能上传不大于".concat(String.valueOf(maxSize)).concat("字节的文件。"));
                    } else {
                        String newFilename = createFileName(extension);
                        File target = new File(todayDir, newFilename);

                        ur = new UploadResponse(UploadResponse.SC_OK, UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr.concat(todayDirStr).concat("/"), true, ConnectorHandler.isFullUrl()).concat(newFilename));

                        try {
                            FileUtil.copyFile(files[i], target);
                        } catch (Exception e) {
                            return new UploadResponse(UploadResponse.SC_ERROR);
                        }
                    }
                }
            }
        }
        return ur;
    }

    private synchronized String createFileName(String extension) {
        Date dt = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String fileName = sdf.format(dt).concat(".").concat(extension);
        return fileName;
    }
}
